<template>
  <div>
    <!-- 按钮 -->
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0" @click="showDialog">添加</el-button>
    <!-- 表格 
    align 标题的对齐方式
    prop:列对应的字段名
    -->

    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" prop="date" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="date" label="品牌LOGO" width="width">
        <template slot-scope="{row, $index}">
          <img :src="row.logoUrl" alt="" style="width:100px; height:100px">
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作" width="widtn">
        <template slot-scope="{row,$index}">
          <el-button type="warning" icon="el-icon-edit" size="mini" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top:20px;textAlign:center" layout="prev, pager, next, jumper, ->,sizes, total"
      :current-page="page" :page-size="limit" :pager-count='7' :total="total" :page-sizes="[3, 5, 10]"
      @current-change="getPageList" @size-change="handleSizeChange">
    </el-pagination>
    <!-- 对话框
    :visible.sync:控制对话框的显示与隐藏
     -->
    <el-dialog :title="tmForm.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
      <!-- form表单 -->
      <el-form style="width:70%" :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
          <!-- 收集图片元素不能使用v-model，因为不是表单元素 -->
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'tradeMark',
  data () {
    return {
      //分页器页码
      page: 1,
      //当前页数展示条数
      limit: 3,
      //总共数据的条数
      total: 0,
      //商品列表
      list: [],
      dialogFormVisible: false,
      //上传图片的属性
      imageUrl: '',
      tmForm: {
        //   收集表单信息
        tmName: '',
        logoUrl: ''
      },
      //   表单验证对象
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请选择品牌图片' },
        ],
      }
    };
  },
  mounted () {
    this.getPageList()
  },
  methods: {

    //获取品牌列表的数据
    async getPageList (pager = 1) {
      this.page = pager
      const { page, limit } = this
      let result = await this.$api.trademark.reqTradeMarkList(page, limit)
      if (result.code == 200) {
        this.total = result.data.total
        this.list = result.data.records
      }
    },
    handleCurrentChange (pager) {
      this.page = pager

    },
    //   分页器某一页需要展示的条数发生改变时触发
    handleSizeChange (limit) {
      this.limit = limit
      this.getPageList()
    },
    //点击添加品牌的按钮
    showDialog () {
      this.dialogFormVisible = true
      //   清除数据
      this.tmForm = { tmName: '', logoUrl: '' }
    },
    // 修改
    updateTradeMark (row) {
      // 浅拷贝不更改数组中的数据
      this.tmForm = { ...row }
      this.dialogFormVisible = true
    },
    // 上传图片成功
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.tmForm.logoUrl = res.data
    },
    // 上传图片之前
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 添加按钮 （添加品牌||修改品牌）
    addOrUpdateTradeMark () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false
          // 发请求
          let result = await this.$api.trademark.reqAddOrUpdateTrademark(this.tmForm)
          if (result.code == 200) {
            this.$message.success(this.tmForm.id ? '添加品牌信息成功' : "添加品牌成功")
            // 添加修改品牌之后需要重新获取列表
            // 如果添加品牌,停留在第一页,如果修改品牌,留在当前页
            this.getPageList(this.tmForm.id ? this.page : 1);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //删除品牌信息
    deleteTradeMark (row) {
      // 弹窗
      this.$confirm(`确定删除${row.tmName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await this.$api.trademark.reqDeleteTradeMark(row.id);
        if (result.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          //   再次获取品牌列表数据
          this.getPageList(this.list.length>1?this.page:this.page-1);
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }

}

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>